<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm"  :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="指导人" prop="mentor">
        <el-input
          v-model="queryParams.mentor"
          placeholder="请输入指导人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择" clearable  @keyup.enter.native="handleQuery">
          <el-option  key="0"  label="未反馈" value="0" />
          <el-option  key="1"  label="已反馈" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="borrowType">
        <el-date-picker v-model="dateRange" type="daterange" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                        style="width: 240px"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search"  @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh"  @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="guidanceList" :height="tableHeight" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="指导人" align="center" prop="mentor" :show-overflow-tooltip="true" />
      <el-table-column label="指导内容" align="center" prop="suggestions" :show-overflow-tooltip="true">
<!--        <template slot-scope="scope">-->
<!--          <div v-html="scope.row.suggestions"></div>-->
<!--        </template>-->
      </el-table-column>
      <el-table-column label="状态" align="center" prop="state" :show-overflow-tooltip="true" >
        <template slot-scope="scope">
          <p v-if="scope.row.state==1">
            已反馈
          </p>
          <p v-if="scope.row.state==0">
            未反馈
          </p>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-document"
            @click="handleDetail(scope.row)"
            v-hasPermi="['archive:supervision:guidance:detail']"
          >详情</el-button>
          <el-button
            type="text"
            icon="el-icon-chat-dot-round"
            @click="handleDiscuss(scope.row)"
            v-hasPermi="['archive:supervision:guidance:discuss']"
          >讨论</el-button>
          <el-button v-if="scope.row.state==0"
                     type="text"
                     icon="el-icon-edit"
                     @click="handleFeedback(scope.row)"
                     v-hasPermi="['archive:supervision:guidance:feedback']"
          >反馈</el-button>
          <el-button  v-if="scope.row.state==1"
                      type="text"
                      icon="el-icon-document"
                      @click="handleFeedbackContent(scope.row)"
                      v-hasPermi="['archive:supervision:guidance:feedbackContent']"
          >反馈内容</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <el-dialog :title="title" :visible.sync="open" width="35%" style="margin-top:8%" append-to-body :before-close="closeDelDialog">
      <div style="overflow-y: auto; height: 250px">
        <el-input
          type="textarea"   :autosize="{ minRows: 6}" :readonly="istype==1?true:false"
          :rows="2"
          placeholder="请输入内容"
          v-model="feedback">
        </el-input>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFeedback" v-if="istype==0">确 定</el-button>
        <el-button @click="closeDelDialog">取 消</el-button>
      </div>
    </el-dialog>



    <el-dialog title="查看详情" :visible.sync="openSupervises" width="70%"  append-to-body :before-close="closeDelDialog1">
      <template>
        <div>
          <el-form ref="form" :model="form" label-width="80px">
            <el-row ref="refbut" style="width:80%;margin:0 auto">
              <el-col :span="24" class="df transf-title-row">
                <el-form-item label="指导人" >
                  {{form.mentor}}  
                </el-form-item>
              </el-col>

              <el-col :span="24" class="df transf-title-row">
                <el-form-item label="指导建议" >
             
                  <editor v-model="form.suggestions" :min-height="400" readOnly="true"/>
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="上传附件" >
                  <div v-for="item in uploadList" :key="item" style="display: flex; margin-left: 1%">
                    <span style="padding: 0 5px">{{ item.docName }}</span>
                    <p v-if="isFbState" style="border-bottom: 1px solid red;">
                      <span v-for="(i, idx) in renyuanOptions" :key="idx">
                        {{ item.mj == i.dictValue ? i.dictLabel : '' }}
                      </span>
                    </p>
                    <el-button type="text"  @click="onPreviewTap(item)" style="margin-left:10px">预览</el-button>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <el-table height="300" style="width:90%;margin:0 auto" v-loading="loading" :data="dataList" :row-key="getRowKeys" :expand-row-keys="expands" @cell-dblclick="celldblclick"
                    border @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="序号" sortable align="center" type="index" />
            <el-table-column type="expand">
              <template slot-scope="props" v-if="props.row.children.length > 0">
                <el-table :data="props.row.children" style="width:88%;margin-left:10%" border>
                  <el-table-column label="档号" align="center" prop="dh" :show-overflow-tooltip="true" />
                  <el-table-column label="题名" align="center" prop="title" :show-overflow-tooltip="true" />
                  <el-table-column label="档案门类" align="center" prop="categoryCode" :show-overflow-tooltip="true"></el-table-column>
                  <el-table-column label="全宗号" align="center" prop="qzh" :show-overflow-tooltip="true"/>
                  <el-table-column label="分类" align="center" prop="type" width="120">
                    <template slot-scope="scope">
                      <p v-if="scope.row.type==1">
                        组卷
                      </p>
                      <p v-if="scope.row.type==0">
                        组件
                      </p>
                    </template>
                  </el-table-column>
                  <el-table-column label="来源" align="center" prop="source" width="120">
                    <template slot-scope="scope">
                      <p v-if="scope.row.source=='1'">
                        档案整理
                      </p>
                      <p v-if="scope.row.source=='0'">
                        文件整理
                      </p>
                    </template>
                  </el-table-column>
                  <el-table-column label="添加时间" align="center" prop="createTime" width="160" />
                </el-table>
              </template>
            </el-table-column>
            <el-table-column label="档号" align="center" prop="dh" :show-overflow-tooltip="true" />
            <el-table-column label="题名" align="center" prop="title" :show-overflow-tooltip="true" />
            <el-table-column label="档案门类" align="center" prop="categoryCode" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column label="全宗号" align="center" prop="qzh" :show-overflow-tooltip="true"/>
            <el-table-column label="分类" align="center" prop="type" width="120">
              <template slot-scope="scope">
                <p v-if="scope.row.type==1">
                  组卷
                </p>
                <p v-if="scope.row.type==0">
                  组件
                </p>
              </template>
            </el-table-column>
            <el-table-column label="来源" align="center" prop="source" width="120">
              <template slot-scope="scope">
                <p v-if="scope.row.source=='1'">
                  档案整理
                </p>
                <p v-if="scope.row.source=='0'">
                  文件整理
                </p>
              </template>
            </el-table-column>
            <el-table-column label="添加时间" align="center" prop="createTime" width="160" />
          </el-table>
          <pagination
            v-show="total1>0"
            :total="total1"
            :page.sync="queryParams1.pageNum"
            :limit.sync="queryParams1.pageSize"
            @pagination="getDaList"
          />
        </div>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDelDialog1">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 预览 -->
    <el-dialog :title="previewTitle" :visible.sync="previewOpen" width="45%" append-to-body >
      <!--
       文件预览
       1、修改添加文件预览istype="1"
       2、查看组件详情istype="2"
       -->
      <FilePreview v-if="item" :item="item" :istype="previewIstype"></FilePreview>
    </el-dialog>

    <!-- 讨论 -->
    <el-dialog title="讨论" :visible.sync="discussOpen" width="25%" append-to-body :before-close="closeDiscuss" @opened="scrollToBottom" @closed="stopInterval">
      <el-card class="box-card">
        <div class="head" ref="messageContainer">
          <div v-for="item in messages" class="message">
            <div v-if="item.float == 'left'" class="message-left">
              <div class="message-time-left">{{item.creator}} {{item.time}}</div>
              <div class="message-text-left">{{ item.content }}</div>
            </div>
            <div v-else class="message-right">
              <div class="message-time-right">{{item.time}} {{item.creator}}</div>
              <div class="message-text-right">{{ item.content }}</div>
            </div>
          </div>
        </div>
        <div class="bottom" v-show="isShowSend">
          <el-input v-model="message" style="width: 75%"/>
          <el-button type="primary" style="margin-left: 1%" @click="sendMessage">发送</el-button>
        </div>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDiscuss">关 闭</el-button>
      </div>
    </el-dialog>


    <!--start  组件详情 -->
    <jianDetailsOpen v-if="jianDetailsOpen" :open="jianDetailsOpen"
                     :celldbData="celldbData" @detailsHandleClose="detailsHandleClose">
    </jianDetailsOpen>
    <!--end 组件详情 -->
    <!-- start 组卷\项目详情 -->
    <juanDetailsOpen v-if="juanDetailsOpen" :open="juanDetailsOpen" :celldbData="celldbData"
                     @detailsHandleClose="detailsHandleClose"></juanDetailsOpen>
    <!-- end 组卷\项目详情 -->
  </div>
</template>

<script>
import {daList, listDaList,listHdList, uploadFileList} from "@/api/archive/supervision/supervises/supervises";
import {
  listGuidanceList,
  updateGuidanceList,
  getDetail,
  getDiscussList, addDiscuss
} from "@/api/archive/supervision/guidance/guidance"
import FilePreview from "@/views/archive/supervision/supervises/filePreview";
import {getLastIndexOf} from "@/utils";
import {getthbytreenodeHeaderList} from "@/api/archive/warehouseManagement/upDownShelves";
import jianDetailsOpen from "@/components/componentsJianDetails";
import juanDetailsOpen from "@/components/componentsJuanDetails";
import estimateTableHeight from "@/mixins/estimateTableHeight";
import { getDicts_archive } from '@/api/archive/dict/dictManageData'
import { fbstat } from "@/api/archive/fileCollection/offlinReception.js";
import {
  getdamjbyrymj
} from "@/api/archive/fileCollection/offlinReception.js";
export default {
  components: { FilePreview, jianDetailsOpen, juanDetailsOpen },
  mixins: [estimateTableHeight],// 混入方法
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      total1:0,
      // archiveBorrowCar表格数据
      guidanceList: [],
      // 弹出层标题
      title: "",
      istype:0,
      // 是否显示弹出层
      open: false,
      //对象
      supervision:{
        id:"",
        feedbackContent:undefined,
        state:undefined

      },
      dataList:[],
      minRows:'',
      feedback:undefined,
      openSupervises:false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        mentor: null,
        state: null
      }, queryParams1: {
        pageNum: 1,
        pageSize: 10,
        supervisionId:undefined
      },
      dateRange: [],
      // 表单参数
      form: {
        id: undefined,
        suggestions: undefined,
        mentor: undefined,
        daIds:undefined
      },
      // 表单校验
      rules: {
      },

      uploadList: [],
      // 预览标题
      previewTitle: '',
      previewOpen: false,
      item: '',
      previewIstype: '1',
      // 讨论
      discussOpen: false,
      messages: [],
      message: undefined,
      tooltipOpen: true,
      formId: '',
      isShowSend: false,
      intervalId: null, // 定时器ID
      // 获取row的key值
      getRowKeys(row) {
        return row.id;
      },
      // 要展开的行，数值的元素是row的key值
      expands: [],
      jianDetailsOpen: false,//件详情弹窗
      juanDetailsOpen: false,//卷详情弹窗
      renyuanOptions: [],//密级下拉列表
      isFbState: false,
    };
  },
  created() {
    this.getList();
    fbstat().then(res => {  //false=不是分保，true=是分保 
      this.isFbState = res.data
      if (this.isFbState) {
        //密级下拉列表
        getDicts_archive("MJ").then(res => { //人员密级
          getdamjbyrymj().then(resdata => { //此接口没有返回dictLabel，需要组装接口
            console.log(resdata, "------------------------")
            var mjdata = [];
            for (var i in resdata.data) {
              for (var j in res.data) {
                if (resdata.data[i].daMj == res.data[j].dictValue) {
                  mjdata.push(res.data[j])
                }
              }
            }

            this.renyuanOptions = mjdata
            console.log(this.renyuanOptions, "------------------------------------------")

          })
        })
      }
    })
  },
  methods: {
    /** 查询archiveBorrowCar列表 */
    getList() {
      this.loading = true;
      listGuidanceList(this.queryParams).then(response => {
        this.guidanceList = response.rows;
        for (let i = 0; i < response.rows.length; i++) {
          const parser = new DOMParser();
          const doc = parser.parseFromString(response.rows[i].suggestions, 'text/html');
          this.guidanceList[i].suggestions = doc.body.textContent   || ""
        }
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        feedback:null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if(this.dateRange != null) {
        if (this.dateRange.length != 0) {
          this.queryParams.createTime = this.dateRange[0].toString()
          this.queryParams.edCreateTime = this.dateRange[1].toString()
        }
      }
      this.getList();
      this.queryParams.createTime = ""
      this.queryParams.edCreateTime = ""

    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.carId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    }, closeDelDialog() {
      this.open=false
      /*   this.closeDelDialog=false
         this.$emit("printCancel")*/
    },
    handleFeedback(row) {
      this.istype=0;
      this.open = true;
      this.title = "反馈";
      this.feedback=undefined;
      this.supervision={};
      this.supervision.id=row.id;
      this.supervision.state=1;

    },submitFeedback(){
      if(this.feedback==undefined){
        this.$modal.msgWarning("请输入反馈内容");
      }else {
        const regex = /^\s*$/;
        if (regex.test(this.feedback)) {
          this.$message.error('不能输入全部空格');
          return false;
        }
        this.supervision.feedbackContent = this.feedback;
        updateGuidanceList(this.supervision).then(response => {
          this.$modal.msgSuccess("反馈成功");
          this.open = false;
          this.getList();
        });
      }
    },handleFeedbackContent(row){
      this.istype=1;
      this.feedback=row.feedbackContent;
      this.open=true;
      this.title="反馈内容";
    },getDaList(){

      listHdList(this.queryParams1).then(response => {
        this.dataList = response.rows;
        for (let i = 0; i < this.dataList.length; i++) {
          daList({daId: this.dataList[i].daId}).then(res=>{
            this.dataList[i].children = res.rows
          })
        }
        this.total1 = response.total;
      });
    },
    handleDetail(row){
      const id = row.id
      getDetail(id).then(resposne => {
        this.reset1();
        this.form = resposne.data;
        // this.queryParams1.supervisionId=id
        // this.getDaList();
        // this.getFileList()
        this.openSupervises = true;

        console.log(this.form,"---------------------------")
      })

    },reset1() {
      this.form = {
        id: undefined,
        suggestions: undefined,
        mentor: undefined,
        daIds: undefined
      }
    },closeDelDialog1() {
      this.openSupervises=false
      this.queryParams1= {
        pageNum: 1,
          pageSize: 10,
          supervisionId:undefined
      }
      /*   this.closeDelDialog=false
         this.$emit("printCancel")*/
    },
    getFileList() {
      uploadFileList({supervisionId: this.queryParams1.supervisionId}).then(response=>{
        this.uploadList = response.rows
      })
    },
    // 预览
    onPreviewTap(item) {
      this.previewTitle = item.docName
      this.previewOpen = true
      this.item = item
    },
    handleDiscuss(row) {
      const id = row.id
      this.formId = id
      if(row.state == '1') {
        this.isShowSend = false
      } else {
        this.isShowSend = true
      }
      this.getDiscuss(id)
    },
    getDiscuss(id) {
      getDiscussList({supervisionId: id}).then(response=>{
        console.log(response)
        this.messages = []
        for (let i = 0; i < response.rows.length; i++) {
          if(response.rows[i].createId == response.rows[i].loginId){
            this.messages.push({
              content: response.rows[i].discussionContent,
              time: response.rows[i].createTime,
              float: 'right',
              creator: response.rows[i].createName
            })
          } else {
            this.messages.push({
              content: response.rows[i].discussionContent,
              time: response.rows[i].createTime,
              float: 'left',
              creator: response.rows[i].createName
            })
          }
        }
        this.discussOpen = true
      })
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messageContainer;
        container.scrollTop = container.scrollHeight;
      });
      // 打开页面每5分钟刷新一次消息列表
      this.intervalId = setInterval(() => {
        this.getDiscuss(this.formId)
      }, 5 * 60 * 1000); // 每5分钟 = 5 * 60秒 * 1000毫秒
    },
    stopInterval() {
      console.log('结束了')
      clearInterval(this.intervalId);
    },
    closeDiscuss() {
      this.discussOpen = false
      this.messages = []
      this.message = ''
      this.formId = ''
    },
    // 发送
    sendMessage() {
      console.log(this.message, this.formId)
      this.form = {
        discussionContent: this.message,
        supervisionId: this.formId
      }
      addDiscuss(this.form).then(response=>{
        this.message = ''
        this.messages = []
        this.getDiscuss(this.formId)
      })
    },
    //关闭详情页面
    detailsHandleClose() {
      this.jianDetailsOpen = false;
      this.juanDetailsOpen = false;
    },
    celldblclick(row) {
      console.log(row, '------------------')
      var level = "";
      if (getLastIndexOf(row.subTableName) == "F") {  //F 件
        level = 0
      } else if (getLastIndexOf(row.subTableName) == "V") { //卷
        level = 1
      } else { //项目
        level = 3
      }
      const menuId = this.$route.meta.menuId
      getthbytreenodeHeaderList(
        {
          categoryId: row.categoryId, menuId: menuId, subTableName: row.subTableName
        }
      ).then(response => {
        var tableHeaderList = response.rows
        this.celldbData = {
          id: row.daId,
          categoryId: row.categoryId,
          menuId: menuId,
          sub_table_name: row.subTableName,
          label: row.title,
          level:level,
          ifSub_table_name:row.subTableName,
          isDel:"0",  //判断是回收站数据还是接收收据 isDel:1  回收站    isDel:0 //离线接收、档案接收、在线接收
          tableHeaderList:tableHeaderList
        }
        this.$nextTick(() => {
          if (getLastIndexOf(row.subTableName) == "F") {  //F 进入件详情
            this.jianDetailsOpen = true;
          } else { //进入卷详情 和项目详情
            this.juanDetailsOpen = true
          }
        })
      })
    },
  }
};
</script>

<style lang="scss" scoped>
.box-card {
  width: 90%;
  margin-left: 5%;
  height: 500px;
  position: relative;
}
.head {
  height: 440px;
  overflow-y: auto; /* 设置垂直滚动条 */
}
.bottom {
  position: absolute;
  bottom: 1%;
  width: 100%;
}

.message{
  margin-bottom: 10px;

  .message-left {
    flex-direction: column;
  }

  .message-right {
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    align-items: flex-end;
  }

  .message-text-left{
    background-color: #f2f2f2;
    padding: 5px;
    border-radius: 5px;
    display: inline-block;
    max-width: 80%;
  }
  .message-time-left{
    font-size: 12px;
    color: #999;
    margin-left: 5px;
  }
  .message-text-right{
    background-color: #e1eaff;
    padding: 5px;
    border-radius: 5px;
    display: inline-block;
    max-width: 80%;
    float: right;
  }
  .message-time-right{
    font-size: 12px;
    color: #999;
    margin-right: 5px;
    float: right;
  }
}
</style>
